// Implement your part 2 solution here
// gcc -lpthread threads.c -o threads

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>

#define NTHREADS 64

char colors[64][64 * 3]; // 64 rows of 64 pixels with 3 color values each (RGB)

void *paint(void *vargp)
{
    int workID = (int)vargp;

    printf("Artist %d is painting\n", workID);
    for (int i = 0; i < 64 * 3; i++)
    {
        colors[workID][i] = workID;
    }
}

void outputPPM()
{
    FILE *fp;
    fp = fopen("threads.ppm", "w+");
    fputs("P3\n", fp);
    fputs("64 64\n", fp);
    fputs("255\n", fp);
    for (int i = 0; i < 64; i++)
    {
        for (int j = 0; j < 64 * 3; j++)
        {
            fprintf(fp, "%d", colors[i][j]);
            fputs(" ", fp);
        }
        fputs("\n", fp);
    }
    fclose(fp);
}

int main(int argc, char **argv)
{
    pthread_t tids[NTHREADS];

    for (int i = 0; i < NTHREADS; i++)
    {
        pthread_create(&tids[i], NULL, paint, (void *)i);
    }

    for (int i = 0; i < NTHREADS; i++)
    {
        pthread_join(tids[i], NULL);
    }

    printf("Masterpiece(threads.ppm) is being assembled\n");
    outputPPM();

    return 0;
}
